﻿@using Flagrum.Web.Components.Controls.Data
@using System.IO
@inject JSInterop Interop

<Button Icon="@Icon" Text="@Text" OnClick="OnClick" CssClass="@CssClass"/>
<InputFile OnChange="OnChange" accept="@AllowedExtensions" id="@_id" class="hidden"/>

@code
{
    private string _id;

    [Parameter]
    public Action<InMemoryFile> OnFileSelected { get; set; }

    [Parameter]
    public Action BeforeFileLoaded { get; set; }

    [Parameter]
    public string Icon { get; set; }

    [Parameter]
    public string Text { get; set; }

    [Parameter]
    public string CssClass { get; set; }

    [Parameter]
    public string AllowedExtensions { get; set; }

    protected override void OnInitialized()
    {
        _id = Guid.NewGuid().ToString();
    }

    private async void OnClick()
    {
        await Interop.ClickElement(_id);
    }

    private async Task OnChange(InputFileChangeEventArgs e)
    {
        BeforeFileLoaded?.Invoke();

        await using var stream = e.File.OpenReadStream(long.MaxValue);
        await using var memoryStream = new MemoryStream();
        await stream.CopyToAsync(memoryStream);

        var file = new InMemoryFile(e.File.Name, memoryStream.ToArray());
        OnFileSelected(file);
    }
}